package com.example.rabbitmq.consumer;

import com.example.rabbitmq.config.DeadLetterConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class DeadLetterConsumer {

    @RabbitListener(queues = DeadLetterConfig.DEAD_QUEUE)
    public void receiveDeadLetter(String message, Channel channel, Message msg) throws IOException {
        try {
            System.out.println("接收到死信消息: " + message + "，时间: " + new Date());

            // 处理死信消息业务逻辑
            processDeadLetter(message);

            // 手动确认
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            System.out.println("死信消息处理失败: " + e.getMessage());
            channel.basicNack(msg.getMessageProperties().getDeliveryTag(), false, false);
        }
    }

    private void processDeadLetter(String message) {
        // 模拟业务处理
        System.out.println("处理死信消息中..." + message);
    }
}
